package com.longge;

import java.util.*;

/**
 * @program: my-code
 * @description:
 * @author: longge
 * @create: 2021-06-02 21:45
 */
public class ZigzagLevelOrder {

    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) return res;
        Deque<TreeNode> queue = new LinkedList<TreeNode>();
        Stack<Integer> stack = new Stack<Integer>();
        int count = 0;
        queue.add(root);
        while (!queue.isEmpty()) {
            List<Integer> col = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (count % 2 == 0) {
                    col.add(node.val);
                } else {
                    stack.push(node.val);
                }
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);

            }
            while (!stack.isEmpty()) {
                col.add(stack.pop());
            }
            res.add(col);
            count++;
        }
        return res;
    }
}
